package com.bwei.wangchao.base;

import android.text.TextUtils;
import android.util.Log;

import com.bwei.wangchao.app.MyApplication;
import com.bwei.wangchao.util.CommonUtil;
import com.bwei.wangchao.util.MD5Encoder;
import com.bwei.wangchao.util.NetUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by lenovo on 2016/11/1.
 */
public abstract class DataBase {

    public static final int ERROR_REQUEST = 100;
    public static final int ERROR_NET = 200;
    private BufferedWriter bufferedWriter = null;


    public void getData(String path, long time) {

        String json = getDataFromLocal(path, time);

        if (TextUtils.isEmpty(json)) {
            getDataFromNet(path, time);
        } else {
            setResultData(json);
        }

    }

    public abstract void setResultData(String json);

    private void getDataFromNet(final String path, final long time) {
        //先判断网络状态
        int netWorkType = NetUtils.getNetWorkType(MyApplication.getContext());

        if (netWorkType != NetUtils.NETWORKTYPE_INVALID) {

            //设置请求参数
            RequestParams requestParams = new RequestParams(path);
            x.http().get(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(final String s) {

                    //使回调时可以得到想要的Json串
                    setResultData(s);
                    Log.i("TAG", "网络请求数据成功");

                    //用线程池操作
                    CommonUtil.poolRunOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //将的到的json串写入本地中
                            writeDataToLocal(path,s, time);


                        }
                    });
                }

                @Override
                public void onError(Throwable throwable, boolean b) {
                    setResultFail(ERROR_REQUEST);
                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            setResultFail(ERROR_NET);
        }

    }

    protected abstract void setResultFail(int errorCode);


    private void writeDataToLocal(String path, String json, long time) {
        //得到本地目录
        File cacheDir = MyApplication.getContext().getCacheDir();
        //创建File指定文件
        File file = null;
        try {
            file = new File(cacheDir, MD5Encoder.encode(path));

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!file.exists()) {
            //判断有没有文件，没有就创建
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {

            //创建输出流写数据
            bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            //第一行写时间
            bufferedWriter.write(System.currentTimeMillis() + time + "\r\n");
            bufferedWriter.write(json);
            bufferedWriter.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private String getDataFromLocal(String path, long time) {

        BufferedReader bufferedReader = null;

        //得到本地目录
        File cacheDir = MyApplication.getContext().getCacheDir();

        //创建File指定文件
        File file = null;
        try {


            file = new File(cacheDir, MD5Encoder.encode(path));

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));

            //读出第一行的时间
            long t = Long.parseLong(bufferedReader.readLine());

            if (System.currentTimeMillis() - t < 0) {
                //利用stringbuilder来append接受得到的字符串
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }

                Log.i("TAG", "本地请求数据成功...");

                return stringBuilder.toString();
            } else {
                Log.i("TAG", "时间太长，从新获取");

                timeDelay();
                getDataFromNet(path, time);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        return null;
    }

    protected abstract void timeDelay();


}
